package com.java1234.jxc.controller.admin;

import com.java1234.jxc.beans.SysLog;
import com.java1234.jxc.beans.SysRole;
import com.java1234.jxc.beans.SysUser;
import com.java1234.jxc.beans.SysUserRole;
import com.java1234.jxc.core.page.Pagination;
import com.java1234.jxc.service.LogService;
import com.java1234.jxc.service.RoleService;
import com.java1234.jxc.service.UserService;
import com.java1234.jxc.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/user")
public class UserAdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private Dao dao;
    @Autowired
    private LogService logService;

    @ResponseBody
    @RequestMapping("/list")
    @RequiresPermissions(value = "用户管理",logical = Logical.OR)
    public Map<String,Object> list(SysUser user,
                                   @RequestParam(value = "page",required = false)Integer page,
                                   @RequestParam(value = "rows",required = false)Integer rows)throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        Cnd cnd = Cnd.where("id","!=","1");
        if (user!=null&&user.getUserName()!=null){
            cnd.and("userName","like","%"+user.getUserName()+"%");
        }
        cnd.asc("id");

        Pagination pagination = userService.listPage(page, rows, cnd);
        int total = pagination.getTotalCount();
        List<SysUser> userList = (List<SysUser>)pagination.getList();

      for (SysUser u:userList){
          List<SysRole> roleList = roleService.findByUserId(u.getId());
          StringBuffer sb=new StringBuffer();
          for(SysRole r:roleList){
              sb.append(","+r.getName());
          }
          u.setRoleList(sb.toString().replaceFirst(",", ""));

      }

        resultMap.put("rows",userList);
        resultMap.put("total",total);

        logService.insert(new SysLog(SysLog.SEARCH_ACTION,"用户列表查询"));
        return resultMap;
    }

    /**
     * 添加或者修改用户信息
     * @param user
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/save")
    @RequiresPermissions(value = "用户管理")
    public Map<String,Object> save(SysUser user) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        if (user.getId()==null){
            if (userService.findByUserName(user.getUserName())!=null){
                resultMap.put("success",false);
                resultMap.put("errorInfo","用户名已经存在!");
                return resultMap;
            }
            SysUser insert = userService.insert(user);
            logService.insert(new SysLog(SysLog.ADD_ACTION,insert.toString()));
        }else{
            SysUser fetch = userService.fetch(user.getId());
            if (!fetch.getUserName().equals(user.getUserName())){
                if (userService.findByUserName(user.getUserName())!=null){
                    resultMap.put("success",false);
                    resultMap.put("errorInfo","用户名已经存在!");
                    return resultMap;
                }
            }

            userService.updateIgnoreNull(user);
            logService.insert(new SysLog(SysLog.UPDATE_ACTION,user.getId()+""));
        }
        resultMap.put("success",true);

    return resultMap;
    }


    /**
     * 删除用户信息
     * @param id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/delete")
    @RequiresPermissions(value = "用户管理")
    public Map<String,Object> delete(Integer id) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        logService.insert(new SysLog(SysLog.DELETE_ACTION,dao.fetch(SysUser.class,id).toString()));
        userService.delete(id);
        dao.clear(SysUserRole.class,Cnd.where("user_id","=",id));
        resultMap.put("success",true);

        return resultMap;
    }
    @ResponseBody
    @RequestMapping("/saveRoleSet")
    @RequiresPermissions(value = "用户管理")
    public Map<String,Object> delete(String roleIds,Integer userId) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();

        if (StringUtil.isNotEmpty(roleIds)&&userId!=null){
            List<String> roleList = Arrays.asList(roleIds.split(","));

        dao.clear(SysUserRole.class,Cnd.where("user_id","=",userId));
        roleList.forEach(item->{
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(Integer.parseInt(item));
            userRole.setUserId(userId);
            dao.insert(userRole);
        });
        resultMap.put("success",true);
        }else{
            dao.clear(SysUserRole.class,Cnd.where("user_id","=",userId));
            resultMap.put("success",true);
        }

        logService.insert(new SysLog(SysLog.UPDATE_ACTION,"saveRoleSet"));

        return resultMap;
    }


    /**
     * 修改密码
     * @param newPassword
     * @param session
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/modifyPassword")
    @RequiresPermissions(value = "修改密码")
    public Map<String,Object> modifyPassword(String newPassword, HttpSession session) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        SysUser currentUser = (SysUser) session.getAttribute("currentUser");
        SysUser user = userService.fetch(currentUser.getId());
        user.setPassword(newPassword);
        dao.update(user);
        resultMap.put("success",true);
        dao.insert(new SysLog(SysLog.UPDATE_ACTION,"修改密码"));

        return resultMap;
    }

    /**
     *
     * @param session
     * @return
     * @throws Exception
     */
    //@ResponseBody
    @RequestMapping("/logout")
    @RequiresPermissions(value = "安全退出")
    public String logout(HttpSession session)throws Exception{
        dao.insert(new SysLog(SysLog.LOGOUT_ACTION,"用户注销"));
        SecurityUtils.getSubject().logout();
        return "redirect:/login.html";
    }




}
